const getUserInfo = require('../services/getUserInfo')
const { encrypt } = require('../services/encrypt')
const User = require('../model/User')

module.exports = {
    userNew: async (ctx, next) => {
        try {
            const postData = ctx.request.body
            const {
                account,
                password,
                email
            } = postData
            const newPassword = encrypt(password)
            const portrait_id = 1
            const oldUser = (await User.findOne({
                where: {
                    account: account
                }
            }))
            console.log(oldUser)
            if (oldUser) {
                ctx.body = {
                    'statusCode': 0,
                    'statusMsg': '账户已存在'
                }
                return
            }
            const user = Object.assign(postData, {
                password: newPassword,
                portraitId: 1,
                username: account
            })
            await User.upsert(user)
            ctx.session.currentUser = account
            ctx.body = {
                'statusCode': 1
            }
        } catch (err) {
            ctx.body = {
                'statusCode': 0,
                'statusMsg': '出错了'
            }
        }
    },

    userDetail: async (ctx, next) => {
        const user = ctx.session.currentUser
        if (user) {
            const userinfo = await getUserInfo(user)
            const account = (await User.findOne({
                where: {
                    account: user
                }
            })).dataValues
            delete account.password
            const info = {
                statusMsg: {
                    account,
                    imageUrl: userinfo.statusMag.imageUrl
                },
                statusCode: 1
            }
            ctx.json(info)
        } else {
            const info = {
                statusCode: 0
            }
            ctx.json(info)
        }
    }
}